package com.aiyige.page.my.settings.acount;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventPasswordSuccess;
import com.aiyige.model.Oauth2ResetPassword;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.vondear.rxtools.RxTool;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 修改密码或钱包密码（输入）
 * xiachao
 */
@Route(path = ARouterConfig.ChangePasswordInputPage)
public class ChangePasswordInputPage extends BaseActivity {
    public static final String TAG = ChangePasswordInputPage.class.getSimpleName();

    /**
     * 修改登录密码
     */
    public static final int CHANGE_TYPE_LOGIN_PASSWORD = 1;

    /**
     * 修改钱包密码
     */
    public static final int CHANGE_TYPE_WALLET_PASSWORD = 2;

    @BindView(R.id.iv_password_visible)
    ImageView ivPasswordVisible;

    @BindView(R.id.tv_username)
    TextView tvUserName;

    @BindView(R.id.et_login_password)
    EditText etLoginPassword;

    @BindView(R.id.btn_finish)
    Button btnFinish;

    boolean isPasswordVisible = false;

    @Autowired
    public String code;

    @Autowired
    public int changeType = CHANGE_TYPE_LOGIN_PASSWORD;

    String mobile = AccountUtil.getMobile() == null ? "":AccountUtil.getMobile();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_change_password_input);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        etLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                checkPassword(s.toString());
            }
        });

        etLoginPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
        etLoginPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event)  {
                if (actionId==EditorInfo.IME_ACTION_DONE
                        ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)) {
                    doSetPassword();
                    return true;
                }
                return false;
            }
        });
        tvUserName.setText(mobile);
        checkPassword(null);
    }

    private void checkPassword(String password) {
        btnFinish.setEnabled(!isEmpty(password));
    }

    private void doSetPassword() {
        showLoading();
        ApiManager.getService().oauth2ResetPassword(code, new Oauth2ResetPassword(mobile, RxTool.Md5(getPassword()))).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {
                hideLoading();
                try {
                    if (response.isSuccessful()) {
                        EventBus.getDefault().post(new EventPasswordSuccess());
                        ARouter.getInstance().build(ARouterConfig.ChangePasswordSuccessPage).navigation();
                        finish();
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        onFailure(call, new Throwable(data.getMessage()));
                    }

                } catch (Exception e) {
                    onFailure(call, new Throwable(response.errorBody().toString()));
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });

    }

    private String getPassword() {
        return etLoginPassword.getText().toString();
    }

    @OnClick({R.id.rl_back, R.id.iv_password_visible, R.id.rl_password_visible, R.id.btn_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.iv_password_visible:
            case R.id.rl_password_visible:
                isPasswordVisible = !isPasswordVisible;
                ivPasswordVisible.setImageResource(isPasswordVisible?R.drawable.login_eye_y:R.drawable.login_eye_n);
                etLoginPassword.setTransformationMethod(isPasswordVisible? HideReturnsTransformationMethod.getInstance(): PasswordTransformationMethod.getInstance());
                etLoginPassword.setSelection(isEmpty(getPassword())?0:getPassword().length());
                break;
            case R.id.btn_finish:
                if (!TextUtils.isEmpty(getPassword()) && getPassword().length() < 6) {
                    ToastX.show(getString(R.string.password_length_is_not_correct));
                    return;
                }
                doSetPassword();
                break;
        }
    }

}
